<script setup lang="ts">
import { ElButton, ElTable, ElTableColumn, ElPopconfirm, ElDialog, ElInput, ElMessage } from "element-plus"
import { inject, onMounted, ref } from "vue";
const axios: any = inject("axios")

const messages = ref([])

interface messageInt{
  id:Number,
  comment:string,
  answer:string,
  date:string
}
const message = ref<messageInt>({
  id:0,
  comment:"",
  answer:"",
  date:""
})

const dialogVisible = ref(false)

const onload = async () => {
  let result = await axios.get(`/message/list`);

  if (result.data.code == 200) {
    messages.value = result.data.data
  }
}

const handleEdit = (row: messageInt) => {
  console.log(row);
  dialogVisible.value=true
  message.value=row
}

const update = async () => {
  let result = await axios.put(`/message/update`,{id:message.value.id,answer:message.value.answer})
  if (result.data.code == 200) {
    ElMessage({
      message: '回复成功',
      type: 'success',
    })
  } else {
    ElMessage.error('回复失败')
  }
  dialogVisible.value=false
  onload()
}

const remove = async (id: number) => {
  let result = await axios.delete(`/message/delete/?id=${id}`)
  if (result.data.code == 200) {
    ElMessage({
      message: '删除成功',
      type: 'success',
    })
  } else {
    ElMessage.error('删除失败')
  }
  onload()
}

onMounted(() => {
  onload()
})

</script>

<template>
  <div style="padding: 10px">
    <el-table :data="messages" border stripe style="width: 100%">
      <!-- <el-table-column prop="id" label="ID" sortable /> -->
      <el-table-column prop="comment" label="留言" />
      <el-table-column prop="answer" label="回答" />
      <el-table-column prop="date" label="日期" />
      <el-table-column fixed="right" label="操作">

        <template #default="scope">
          <el-button text @click="handleEdit(scope.row)">编辑</el-button>
          <el-popconfirm title="确认删除吗？"  @confirm="remove(scope.row.id)">
            <template #reference>
              <el-button text >删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog v-model="dialogVisible" title="提示" width="30%">
      <el-form-item label="回答">
        <el-input v-model="message.answer" style="width: 80%" />
      </el-form-item>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="update()">确认</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<style scoped>
</style>
